﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using MedicalCare.EntityDefinitions.Entities;
using MedicalCare.Messages;
using MedicalCare.Translator;
using MedicalCare.Utilities;
using NHibernate.Criterion;
using NHibernate.Transform;
using StructureMap;
using NHibernate;

namespace MedicalCare.DbLayer.Adaptors
{
    public class UserAdaptor: IUserAdaptor
    {
        private ISession _mcSession;

        public UserAdaptor()
        {
            _mcSession = ObjectFactory.GetNamedInstance<ISession>("MedicalCareSession");
        }

        public IList<UserEntity> GetUsers(string orderKey, string orderVal,
                          int pageIndex, int pageSize, string whereStr)
        {
            try
            {
                //var translator = ObjectFactory.GetInstance<IUserInfoToUserMessage>();
                var query = _mcSession.CreateSQLQuery(@" EXEC Users_Paging_GET @PAGEINDEX=:PAGEINDEX, @PAGESIZE=:PAGESIZE, @ORDERKEY=:ORDERKEY, @ORDERVAL=:ORDERVAL, @WHERE=:WHERE ")
                            .SetInt32("PAGEINDEX", pageIndex)
                            .SetInt32("PAGESIZE", pageSize)
                            .SetString("ORDERKEY", orderKey)
                            .SetString("ORDERVAL", orderVal)
                            .SetString("WHERE", whereStr)
                            .SetResultTransformer(Transformers.AliasToBean<UserEntity>());
                var bpList = query.List<UserEntity>();

                return bpList;
            }
            catch (Exception ex)
            {
                //return false;
            }
            return null;
        }

        public IList<UserEntity> GetUsers(string orderKey, string orderVal, string whereStr)
        {
            try
            {
                //var translator = ObjectFactory.GetInstance<IUserInfoToUserMessage>();
                var query = _mcSession.CreateSQLQuery(@" EXEC Users_GET @ORDERKEY=:ORDERKEY, @ORDERVAL=:ORDERVAL, @WHERE=:WHERE ")
                            .SetString("ORDERKEY", orderKey)
                            .SetString("ORDERVAL", orderVal)
                            .SetString("WHERE", whereStr)
                            .SetResultTransformer(Transformers.AliasToBean<UserEntity>());
                var bpList = query.List<UserEntity>();

                return bpList;
            }
            catch (Exception ex)
            {
                //return false;
            }
            return null;
        }

        public int GetRecordsTotal(string whereStr)
        {
            try
            {
                //var translator = ObjectFactory.GetInstance<IUserInfoToUserMessage>();
                var query = _mcSession.CreateSQLQuery(@" EXEC Users_Paging_Total @WHERE=:WHERE ")
                          .SetString("WHERE", whereStr)
                          .SetResultTransformer(Transformers.AliasToBean<TotalEntity>());

                var result = query.List<TotalEntity>().FirstOrDefault().Total;

                return result;
            }
            catch (Exception ex)
            {
                //return false;
            }
            return 0;
        }

        public UserMessage LoadCurrentUser(LoginMessage message)
        {
            var translator = ObjectFactory.GetInstance<IUserInfoToUserMessage>();

            try
            {
                // Load user Info
                var userList = _mcSession.CreateCriteria<UserEntity>()
                    .Add(Restrictions.Eq("Name", message.Name))
                    .Add(Restrictions.Eq("Password", message.Password))
                    .List<UserEntity>().FirstOrDefault();

                return translator.Translate(userList);
            }
            catch(Exception ex)
            {
                return new UserMessage()
                           {
                               Success = false,
                               Description = ex.Message,
                               ErrorType = ErrorTypes.DBEXECUTEERROR.ToString()
                           };
            }
        }

        public int Update(UserMessage msg)
        {
            var result = default(int);
            try
            {
                if (msg.Id > 0)// update
                {
                    // TODO: 如果设备id大于0，说明设备已存在，则是更新设备信息
                }
                else // insert
                {
                    // TODO: 如果设备id为空/0，则是插入改设备
                    //Champion 2013/1/5
                    var query = _mcSession.CreateSQLQuery(@" EXEC Users_Insert @Id=:Id,@Name=:Name,@Password=:Password,@IDNumber=:IDNumber,@Age=:Age,@Gender=:Gender,@Mobile=:Mobile,@Email=:Email,@QQ=:QQ,@PostalCode=:PostalCode,@City=:City,@Province=:Province,@District=:District,@AddressDetail=:AddressDetail,@RoleCode=:RoleCode,@Comment=:Comment,@CreateUser=:CreateUser,@Valid=:Valid ")
                                .SetInt32("Id",msg.Id)
                                .SetString("Name", msg.UserName)
                                .SetString("Password", msg.Password)
                                .SetString("IDNumber", msg.IDNumber)
                                .SetInt32("Age", msg.Age)
                                .SetString("Gender", msg.Gender)
                                .SetString("Mobile", msg.Mobile)
                                .SetString("Email", msg.Email)
                                .SetString("QQ", msg.QQ)
                                .SetString("PostalCode", msg.UserAddress.PostalCode)
                                .SetString("City", msg.UserAddress.City)
                                .SetString("Province", msg.UserAddress.Province)
                                .SetString("District", msg.UserAddress.District)
                                .SetString("AddressDetail", msg.UserAddress.AddressDetail)
                                .SetString("RoleCode", msg.UserRoleCode)
                                .SetString("Comment", msg.Comment)
                                .SetString("Valid", msg.Valid)
                                .SetString("CreateUser", msg.CreateUser)
                               .SetResultTransformer(Transformers.AliasToBean<ResultEntity>());
                    var test = query.List<ResultEntity>();
                    result = test.FirstOrDefault().Id;
                }
            }
            catch (Exception ex)
            {
                result = -1;
            }

            return result;
        }

        public void Remove(UserMessage message)
        {
            throw new NotImplementedException();
        }

        public UserMessage Read(string id)
        {
            throw new NotImplementedException();
        }

        public IList<UserEntity> GetPagingRecords(string orderKey, string orderVal,
            int pageIndex, int pageSize, string whereStr)
        {
            try
            {
                //var translator = ObjectFactory.GetInstance<IUserInfoToUserMessage>();
                var query = _mcSession.CreateSQLQuery(@" EXEC Users_Paging_GET @PAGEINDEX=:PAGEINDEX, @PAGESIZE=:PAGESIZE, @ORDERKEY=:ORDERKEY, @ORDERVAL=:ORDERVAL, @WHERE=:WHERE ")
                            .SetInt32("PAGEINDEX", pageIndex)
                            .SetInt32("PAGESIZE", pageSize)
                            .SetString("ORDERKEY", orderKey)
                            .SetString("ORDERVAL", orderVal)
                            .SetString("WHERE", whereStr)
                            .SetResultTransformer(Transformers.AliasToBean<UserEntity>());
                var bpList = query.List<UserEntity>();

                return bpList;
            }
            catch (Exception ex)
            {
                //return false;
            }
            return null;
        }
        //Champion 2013/1/4
        public int DeleteUserById(UserMessage msg)
        {
            try
            {
                int result = _mcSession.CreateSQLQuery(@" EXEC Users_Delete @Id=:Id,@ModifyUser=:ModifyUser,@Valid=:Valid ")
                           .SetInt32("Id", msg.Id)
                           .SetString("ModifyUser", msg.ModifyUser)
                           .SetString("Valid", msg.Valid)
                           .ExecuteUpdate();

                return result;
            }
            catch (Exception ex)
            {

            }
            return 0;
        
        }

        public IList<UserRoleEntity> GetAllUserRole()
        {
            try
            {
                // HQL
                var userRoleList = _mcSession.CreateCriteria<UserRoleEntity>()
                     .List<UserRoleEntity>();
                return userRoleList;
            }
            catch (Exception ex)
            {
            }
            return null;
        }
        //Champion 2013/1/5
        public IList<ProvinceEntity> GetAllProvince()
        {
            try
            {
                // HQL
                var ProvinceList = _mcSession.CreateCriteria<ProvinceEntity>()
                     .List<ProvinceEntity>();
                return ProvinceList;
            }
            catch (Exception ex)
            {
            }
            return null;
        }
        //Champion 2013/1/5
        public IList<DistrictEntity> GetDistrictListByCityId(int CityID)
        {
            try
            {
                // HQL
                var DistricList = _mcSession.CreateCriteria<DistrictEntity>()
                            .Add(Restrictions.Eq("CityID", CityID))
                            .List<DistrictEntity>();


                return DistricList;
            }
            catch (Exception ex)
            {
            }
            return null;
        }

        public IList<CityEntity> GetCityListByProId(int ProID)
        {
            try
            {
                // HQL
                var CityList = _mcSession.CreateCriteria<CityEntity>()
                            .Add(Restrictions.Eq("ProId", ProID))
                            .List<CityEntity>();

                     
                return CityList;
            }
            catch (Exception ex)
            {
            }
            return null;
        
        }

    }
}
